<?php
namespace app\common\controller;

use think\Cache;
use think\Controller;
use think\Db;

define('TOKEN','tokencode');


class ApiBase extends Controller
{

    protected function _initialize()
    {
        parent::_initialize();
        //$this->getSystem();
    }
    /**
     * 重置token
     */
    protected function set_token($id,$mobile,$wxopenid='')
    {
      	$token_arr=[
          'id'=>$id,
          'mobile'=>$mobile,
          'time'=>time(),
          'token'=>TOKEN,
          'wxopenid'=>$wxopenid
        ];
      	sort($token_arr);
      	$token=implode('',$token_arr);
      	$token=strtoupper(md5($token));
      	$save_token=[
          'token'=>$token,
          'token_time'=>date('Y-m-d H:i:s',time()),
        ];
        $r=Db::table('os_user')->where(['id'=>$id,'mobile'=>$mobile])->update($save_token);
      	if($r){
          return ['Status'=>1,'Message'=>'成功','Data'=>$save_token];
        }else{
          return ['Status'=>0,'Message'=>'失败，重新尝试'];
        }
      	
    }

    /**
     * 刷新token_time
     */
    protected function refresh_token($token)
    {
        
    }
  	/**
     * 验证token
     */
    protected function check_token($id,$token)
    {
        $check=Db::table('os_user')->where(['id'=>$id,'token'=>$token])->find();
      	if(empty($check)){
          return ['Status'=>0,'Message'=>'请重新登录'];
        }
      	$token_time=strtotime($check['token_time']);
      	$now_time=time();
      	if(($token_time+36000)<=$now_time){
          return ['Status'=>0,'Message'=>'已超时，请重新登录'];
        }else{
          Db::table('os_user')->where(['id'=>$id,'token'=>$token])->update(['token_time'=>date('Y-m-d H:i:s',time())]);
          return ['Status'=>1,'Message'=>'token有效'];
        }
    }
    /**
     * 返回数据
     */
    protected function splash($status,$message,$data=[])
    {
        return json(['Status'=>$status,'Message'=>$message,'Data'=>$data]);
    }
  
}